package com.jy.datapipeline.common.support;

import com.jy.datapipeline.common.constants.ExcelConstants;
import com.jy.datapipeline.common.constants.FormatConstants;
import com.jy.datapipeline.common.util.DateTimeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.List;

/**
 * @类名 ExcelSupport
 * @描述
 * @作者 白条君
 * @创建日期 2023/7/5 15:05
 * @版本 1.0
 */
@Component
public class ExcelSupport {

    public void downloadTemplate(HttpServletResponse res, List<String> columns,
                                 List<String> comments, String sheetName, List<String> example, String templateName) throws IOException {
        try (ServletOutputStream outputStream =  res.getOutputStream()) {
            res.reset();
            res.setContentType("application/octet-stream");
            res.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode(
                    templateName + DateTimeUtil.format(FormatConstants.DATE_FORMAT),
                    StandardCharsets.UTF_8.name());
            res.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
            this.generateTemplate(outputStream, columns, comments, sheetName, example);
        } catch (IOException e) {
            res.setHeader("Content-type", "text/html;charset=UTF-8");
            OutputStream ps = res.getOutputStream();
            ps.write("文件下载失败".getBytes(StandardCharsets.UTF_8));
            ps.flush();
            ps.close();
        }
    }

    public void generateTemplate(OutputStream ous, List<String> headers, List<String> comments, String sheetName, List<String> example) throws IOException {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet(sheetName);
        initHeaders(hssfWorkbook, sheet, headers, comments);
        if (!CollectionUtils.isEmpty(example)) {
            initExample(hssfWorkbook, sheet, example);
        }
        hssfWorkbook.write(ous);
        ous.flush();
    }

    private void initHeaders(HSSFWorkbook wb, HSSFSheet mainSheet, List<String> headers, List<String> comments) {
        //表头样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        //字体样式
        HSSFFont fontStyle = wb.createFont();
        fontStyle.setFontName("微软雅黑");
        fontStyle.setFontHeightInPoints((short) 10);
        style.setFont(fontStyle);
        //生成主内容
        HSSFRow rowFirst = mainSheet.createRow(0);//第一个sheet的第一行为标题
//        mainSheet.createFreezePane(0, 1, 0, 1); //冻结第一行
        //写标题
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
            mainSheet.setColumnWidth(i, 5000); //设置每列的列宽
            cell.setCellStyle(style); //加样式
            cell.setCellValue(headers.get(i));
            String comment = comments.get(i);//往单元格里写数据
            if (!StringUtils.isBlank(comment)) {
                HSSFComment hssfComment = initComment(mainSheet, comment);
                cell.setCellComment(hssfComment); //添加注释
            }
        }
    }

    private HSSFComment initComment(HSSFSheet mainSheet, String commentStr) {
        //HSSFPatriarch是所有注释的容器
        HSSFPatriarch hssfPatriarch = mainSheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        HSSFComment comment = hssfPatriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString(commentStr));
        return comment;
    }

    private void initExample(HSSFWorkbook wb, HSSFSheet mainSheet, List<String> example) {
//        CellStyle style = wb.createCellStyle(); //创建CellStyle对象
//        style.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex()); //设置背景色
        HSSFRow rowFirst = mainSheet.createRow(1);
        for (int i = 0; i < example.size(); i++) {
            HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
            mainSheet.setColumnWidth(i, 5000); //设置每列的列宽
            cell.setCellValue(example.get(i));
//            cell.setCellStyle(style);
        }
    }
}
